﻿using System;
using System.Text;
using Wangzeran.CodeMaker.Core.Tag;
using Wangzeran.CodeMaker.Core.Template;
using Wangzeran.CodeMaker.Core.Util;

namespace Wangzeran.CodeMaker.PlugIns.Templates
{
    /// <summary>
    /// 循环表模板
    /// </summary>
    public class ForeachTableTemplate : TemplateSupport
    {
        /// <summary>
        /// 模板名称
        /// </summary>
        public override string TemplateName
        {
            get { return "foreach模板"; }
        }

        /// <summary>
        /// 执行文件模板
        /// </summary>
        /// <param name="templatePath">模板文件路径</param>
        /// <param name="value">值</param>
        /// <param name="fileName">输出文件名称</param>
        /// <returns></returns>
        public override string ExecuteTempldate(string templatePath, object value, out string fileName)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        /// <summary>
        /// 执行文本模板
        /// </summary>
        /// <param name="contents">文本内容</param>
        /// <param name="value">值</param>
        /// <param name="fileName">输出文件名称</param>
        /// <returns></returns>
        public override string ExecuteTempldateContents(string templatePath, string contents, object value, out string fileName)
        {
            try
            {
                fileName = null;
                StringBuilder sb = new StringBuilder(contents);
                string[] lines = StringUtil.SplitString(contents);

                // 读取列信息
                foreach (string line in lines)
                {
                    string[] tags = GetTags(line);
                    foreach (string tagStr in tags)
                    {
                        ITag tag = ParseTag(tagStr);
                        if (tag == null)
                        {
                            sb.Append(tagStr);
                            continue;
                        }
                        string tagResult = tag.Process(tagStr, value);
                        sb = sb.Replace(tagStr, tagResult);
                    }
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {	
                throw ex;
            }
        }
    }
}
